<?php
/**
 * Joomla! 1.5 component NS Pro
 *
 * @version $Id: controller.php 2009-04-28 01:47:12 svn $
 * @author Christopher Mavros
 * @package Joomla
 * @subpackage NS Pro
 * @license GNU/GPL
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

jimport( 'joomla.application.component.controller' );
require_once( JPATH_COMPONENT.DS.'helpers'.DS.'helper.php' );

/**
 * NS Pro Controller
 *
 * @package Joomla
 * @subpackage NS Pro
 */
class NsproController extends JController {

    function __construct() {
        //Get View
        if(JRequest::getCmd('view') == '') {
            JRequest::setVar('view', 'default');
        }
        
        $myview = JRequest::getCmd('view');     

        $this->item_type = 'Default';
        $jversion = new JVersion();
        $this->j15 = ($jversion->RELEASE == '1.5');
        //$this->j16 = ($jversion->RELEASE == '1.6');
        parent::__construct();

        $this->registerTask( 'add'  ,   'edit' );
        
        if ($this->j15 != true) {          
		      JSubMenuHelper::addEntry(JText::_('Mailing List Manager'), 'index.php?option=com_nspro&view=default', $myview == 'default');
		      JSubMenuHelper::addEntry(JText::_('Subscription Manager'), 'index.php?option=com_nspro&view=subscribers', $myview == 'subscribers');
		      JSubMenuHelper::addEntry(JText::_('Newsletter Manager'), 'index.php?option=com_nspro&view=newsletters', $myview == 'newsletters');
		      JSubMenuHelper::addEntry(JText::_('Toolkit'), 'index.php?option=com_nspro&view=toolkit', $myview == 'toolkit');
		      JSubMenuHelper::addEntry(JText::_('HTML Templates'), 'index.php?option=com_nspro&view=templates', $myview == 'templates');
		      JSubMenuHelper::addEntry(JText::_('Additional Fields'), 'index.php?option=com_nspro&view=fields', $myview == 'fields');
		      JSubMenuHelper::addEntry(JText::_('About NS Pro'), 'index.php?option=com_nspro&view=about', $myview == 'about');
		    }
    }

    function display() {
      $db =& JFactory::getDBO();

      if((isset($_POST['task'])) && ($_POST['task'] == 'applyTemplate')) {

        $link = 'index.php?option=com_nspro&controller=nspro&task=nedit&cid[]=' . $_POST['nid'];

        $query = 'SELECT * FROM `#__nspro_html_templates` WHERE `id` = "' . mysql_escape_string($_POST["template_id"]) .'"';
        $db->setQuery($query);
        $template = $db->loadObject();
        if ($template != false) {
          $tcode = $template->tcode;
          // the tcode is escaped, because it usually contains many quotes and double quotes.
          // This way it works fine, although.
          $query = 'UPDATE `#__nspro_newsletters` SET `message` = "' . mysql_escape_string($tcode) . '" WHERE `id` = "' . mysql_escape_string($_POST["nid"]) . '"';
          $db->setQuery($query);
          if ($db->query()) {
            $msg = 'Template Applied';
            $this->setRedirect($link, $msg);
          }
          else {
            $msg = JText::_('Error applying Template') . '. ' . JText::_('Error Code:') . ' ' . '#2';
            $this->setRedirect($link, $msg, 'error');
          }
        }
        else {
          $msg = JText::_('Error applying Template') . '. ' . JText::_('Error Code:') . ' ' . '#1';
          $this->setRedirect($link, $msg, 'error');
        }
      }

      parent::display();
    }

    // SUBSCRIBER FUNCTIONS

    function edit()
    {
        JRequest::setVar( 'view', 'nspro' );
        JRequest::setVar( 'layout', 'form'  );
        JRequest::setVar('hidemainmenu', 1);

        parent::display();
    }

    function qconfirm()
    {
        $array = JRequest::getVar('cid',  0, '', 'array');
        $mId = (int)$array[0];

        $db =& JFactory::getDBO();

        $query = 'UPDATE `#__nspro_subs` SET `confirmed` = "1" WHERE `id` = "'.mysql_escape_string($mId).'"';

        $db->setQuery($query);

        $link = 'index.php?option=com_nspro&view=subscribers';

        if ($db->query()) {
          $msg = 'Subscriber(s) Confirmed';
          $this->setRedirect($link, $msg);
        }
        else {
          $msg = 'Error Confirming Subscriber(s)';
          $this->setRedirect($link, $msg, 'error');
        }

    }

    function quconfirm()
    {
        $array = JRequest::getVar('cid',  0, '', 'array');
        $mId = (int)$array[0];

        $db =& JFactory::getDBO();

        $query = 'UPDATE `#__nspro_subs` SET `confirmed` = "0" WHERE `id` = "'.mysql_escape_string($mId).'"';

        $db->setQuery($query);

        $link = 'index.php?option=com_nspro&view=subscribers';
        if ($db->query()) {
          $msg = 'Subscriber(s) Unconfirmed';
          $this->setRedirect($link, $msg);
        }
        else {
          $msg = 'Error Unconfirming Subscriber(s)';
          $this->setRedirect($link, $msg, 'error');
        }
    }

    function save()
    {
        $model = $this->getModel('subscribers');

        $link = 'index.php?option=com_nspro&view=subscribers';
        $saved = $model->store();
        if ($saved === true) {
          $msg = JText::_( 'Subscriber Saved!' );
          $this->setRedirect($link, $msg);
        }
        else if ($saved !== false) {
          $msg = JText::_('Error:').' '.$saved;
          $this->setRedirect($link, $msg, 'error');
        }
        else {
          $msg = JText::_( 'Error Saving Subscriber' );
          $this->setRedirect($link, $msg, 'error');
        }
    }

    function removeall() {
      $db =& JFactory::getDBO();
      $query = 'DELETE FROM `#__nspro_subs` WHERE 1=1';
      $db->setQuery($query);
      if (!$db->query()) {
        $msg = JText::_( 'Error: One or More Subscribers Could not be Deleted' );
        $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg );
      }
      else {
        $query = 'DELETE FROM `#__nspro_field_values` WHERE 1=1';
        $db->setQuery($query);
        $db->query();
        $msg = JText::_( 'Subscriber(s) Deleted' );
        $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg, 'error');
      }
    }

    function remove()
    {
        $model = $this->getModel('subscribers');
        if(!$model->delete()) {
            $msg = JText::_( 'Error: One or More Subscribers Could not be Deleted' );
            $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg, 'error');
        } else {
            $msg = JText::_( 'Subscriber(s) Deleted' );
            $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg);
        }

        $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg );
    }

    function cancel()
    {
        $msg = JText::_( 'Operation Cancelled' );
        $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg );
    }
    
    function massconfirm()
    {
        $model = $this->getModel('subscribers');
        if(!$model->massconfirm()) {
            $msg = JText::_( 'Error: One or More Subscribers Could not be Confirmed' );
            $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg, 'error');
        } else {
            $msg = JText::_( 'Subscriber(s) Confirmed' );
            $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg);
        }

        $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg );
    }    
    
    function massunconfirm()
    {
        $model = $this->getModel('subscribers');
        if(!$model->massunconfirm()) {
            $msg = JText::_( 'Error: One or More Subscribers Could not be Unconfirmed' );
            $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg, 'error');
        } else {
            $msg = JText::_( 'Subscriber(s) Unconfirmed' );
            $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg);
        }

        $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg );
    }    

    function resendconfirm() {

        //global $mainframe;
        $mainframe = JFactory::getApplication();

        $db =& JFactory::getDBO();

        include('lib.php');

        $confirm_url = 'index.php?option=com_nspro&amp;view=nspro&amp;layout=confirm&amp;nss=nsplgp';
        $uri = & JURI::getInstance();
        $myBase = str_replace('/administrator/', '/', JURI::base());

        $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

        $errors = 0;

        jimport('joomla.application.component.helper');
        $params = JComponentHelper::getParams( 'com_nspro' );
        if ($this->j15 == true) {
          $component = JComponentHelper::getComponent( 'com_nspro' );
          $params = new JParameter( $component->params );
        }

        $fromNameConfirm = $params->get('from_name_confirm', 'Newsletter Subscriber');
        $fromEmailConfirm = $params->get('from_email_confirm', 'newsletter_subscriber@yoursite.com');

        if ($fromNameConfirm == 'Newsletter Subscriber') {
          $fromNameConfirm = $mainframe->getCfg('fromname');
        }
        if ($fromEmailConfirm == 'newsletter_subscriber@yoursite.com') {
          $fromEmailConfirm = $mainframe->getCfg('mailfrom');
        }

        $subjectConfirm = $params->get('subject_confirm', 'Subscription Confirmation');
        $messageConfirm = $params->get('message_confirm', 'Thank you for subscribing at {conf_host} .<br/><br/><br/>{conf_link}Click to complete your Subscription{/conf_link}<br/><br/>or copy this to your address bar<br/><br/>{conf_url}');

        $subjectConfirm = JText::_($subjectConfirm);
        $messageConfirm = JText::_($messageConfirm);

        if (count( $cids )) {
          foreach($cids as $cid) {
            $query = 'SELECT * FROM `#__nspro_subs` WHERE `id` = "'.mysql_escape_string($cid).'"';
            $db->setQuery( $query );
            $msub = $db->loadObject();

            $myConfirmationLink = $myBase.$confirm_url.'&amp;u='.md5($msub->email);

            $myMessage = JString::str_ireplace('{conf_host}', $uri->getHost(), $messageConfirm);
            $myMessage = JString::str_ireplace('{conf_url}', $myConfirmationLink, $myMessage);

            $myMessage = JString::str_ireplace('{conf_link}', '<a href="' . $myConfirmationLink . '">', $myMessage);
            $myMessage = str_replace('{/conf_link}', '</a>', $myMessage);

            if (MySendMailBounceHeader($fromEmailConfirm, $fromNameConfirm, $msub->email, $subjectConfirm, $myMessage, true) !== true) {
              $errors = $errors + 1;
            }
          }
        }

        $link = 'index.php?option=com_nspro&view=subscribers';
        if ($errors > 0) {
          $msg = JText::_( 'Error Sending Confirmation(s)' );
          $this->setRedirect($link, $msg, 'error');
        }
        else {
          $msg = JText::_( 'Confirmation(s) sent!' );
          $this->setRedirect($link, $msg);
        }
    }

    function bouncecheck() {

      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      if ($this->j15 == true) {
        $component = JComponentHelper::getComponent( 'com_nspro' );
        $params = new JParameter( $component->params );
      }
      
      include('lib.php');

      $result = ConnectToBounceAddress($params);

      $link = 'index.php?option=com_nspro&view=subscribers';

      if (strtolower(JString::substr($result, 0, 5)) == 'error') {
        $msg = JText::_('Bounce Check') . ' ' . $result;
        $this->setRedirect($link, $msg, 'error');
      }
      else {
        $msg = JText::_( 'Bounce Check Completed' ) . ': ' . $result;
        $this->setRedirect($link, $msg);
      }
    }

    function doexport($file, $writefunction) {

      $db =& JFactory::getDBO();
      $query = 'SELECT * FROM `#__nspro_subs` ORDER BY `id`';
      $db->setQuery($query);
      $msubs = $db->loadObjectList();

      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      if ($this->j15 == true) {
        $component = JComponentHelper::getComponent( 'com_nspro' );
        $params = new JParameter( $component->params );
      }

      $export_delim = $params->get('export_delimiter', ';');
      $export_time  = $params->get('export_time', '5');
      $export_extra_fields = $params->get('export_extra_fields', '1');

      $handle = fopen($file, 'w');

      if ($handle == false) {
        $msg = JText::_('Error saving file');
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

      $this->$writefunction($msubs, $handle, $db, $export_extra_fields, $export_delim);

      fclose($handle);

      return true;

    }

    function writetxtcsv($msubs, $handle, $db, $exf, $export_delim) {
      $pub = (($exf == '1') ? " WHERE `published` = true" : "");
      if ($exf != '0') {
        $db->setQuery('SELECT `name` FROM `#__nspro_fields`' . $pub);
        $fields = $db->loadObjectList();
      }

      fwrite($handle, '#'.JText::_('Name').$export_delim.
                          JText::_('Email').$export_delim.
                          JText::_('DateTime').$export_delim.
                          JText::_('Confirmed').$export_delim.
                          JText::_('Mailing Lists').$export_delim);
      if ($exf != '0') {
        foreach($fields as $field) {
          fwrite($handle, JText::_($field->name).$export_delim);
        }
      }
      fwrite($handle, "\n#\n");

      foreach ($msubs as $msub) {
        fwrite($handle, $msub->name.$export_delim.
                        $msub->email.$export_delim.
                        $msub->datetime.$export_delim.
                        $msub->confirmed.$export_delim.
                        $msub->mailing_lists.$export_delim);

        $pub2 = (($exf == '1') ? " AND B.`published` = true" : "");
        if ($exf != '0') {
          $db->setQuery('SELECT A.*, B.`name`, B.`published` FROM `#__nspro_field_values` AS A LEFT JOIN `#__nspro_fields` AS B '.
                        'ON A.`field_id` = B.`id` WHERE A.`subscriber_id` = "'.$msub->id.'"' . $pub2);
          $fieldvalues = $db->loadObjectList();
          foreach ($fieldvalues as $fv) {
            fwrite($handle, $fv->value.$export_delim);
          }
        }

        fwrite($handle, "\n");
      }
    }

    function writens($msubs, $handle, $db, $exf, $export_delim) {
      foreach ($msubs as $msub) {
        fwrite($handle, $msub->name.' ('.$msub->email.'); ');
      }
    }

    function writexml($msubs, $handle, $db, $exf, $export_delim) {
      fwrite($handle, '<root>'."\n".'<nspro_xml>'."\n");

      foreach ($msubs as $msub) {
        fwrite($handle, '  <nspro_subscriber id="'.$msub->id.'">'."\n".
                        '    <name>'.$msub->name.'</name>'."\n".
                        '    <email>'.$msub->email.'</email>'."\n".
                        '    <datetime>'.$msub->datetime.'</datetime>'."\n".
                        '    <confirmed>'.$msub->confirmed.'</confirmed>'."\n".
                        '    <mailing_lists>'.$msub->mailing_lists.'</mailing_lists>'."\n");

        $pub = (($exf == '1') ? " AND B.`published` = true" : "");
        if ($exf != '0') {
          $db->setQuery('SELECT A.*, B.`name`, B.`published` FROM `#__nspro_field_values` AS A LEFT JOIN `#__nspro_fields` AS B '.
                        'ON A.`field_id` = B.`id` WHERE A.`subscriber_id` = "'.$msub->id.'"' . $pub);
          $fieldvalues = $db->loadObjectList();
          foreach ($fieldvalues as $fv) {
            fwrite($handle, '    <field name="'.$fv->name.'" id="'.$fv->field_id.'">'.$fv->value.'</field>'."\n");
          }
        }

        fwrite($handle, '  </nspro_subscriber>'."\n");
      }

      fwrite($handle, '</nspro_xml>'."\n".'</root>');
    }

    function exporttxt() {
      $file = 'components/com_nspro/uploads/export_list.txt';

      $exported = $this->doexport($file, 'writetxtcsv');
      
      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      if ($this->j15 == true) {
        $component = JComponentHelper::getComponent( 'com_nspro' );
        $params = new JParameter( $component->params );
      }

      $export_time  = $params->get('export_time', '5'); 

      if ($exported) {
        setcookie('export_txt', MD5('export_txt'), time()+60*$export_time);
        $msg = JText::_( 'Text File Exported' ) . '. <a href="components/com_nspro/uploads/gettxt.php" target="_blank">'.JText::_('Click to download').'.</a>';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
      }
      else {
        $msg = JText::_( 'Error Exporting Text File' );
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

    }

    function exportcsv() {
      $file = 'components/com_nspro/uploads/export_list.csv';

      $exported = $this->doexport($file, 'writetxtcsv');
      
      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      if ($this->j15 == true) {
        $component = JComponentHelper::getComponent( 'com_nspro' );
        $params = new JParameter( $component->params );
      }

      $export_time  = $params->get('export_time', '5');       

      if ($exported) {
        setcookie('export_csv', MD5('export_csv'), time()+60*$export_time);
        $msg = JText::_( 'Excel File Exported' ) . '. <a href="components/com_nspro/uploads/getcsv.php" target="_blank">'.JText::_('Click to download').'.</a>';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
      }
      else {
        $msg = JText::_( 'Error Exporting Excel File' );
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

    }

    function exportns() {
      $file = 'components/com_nspro/uploads/mailing_list.txt';

      $exported = $this->doexport($file, 'writens');
      
      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      if ($this->j15 == true) {
        $component = JComponentHelper::getComponent( 'com_nspro' );
        $params = new JParameter( $component->params );
      }

      $export_time  = $params->get('export_time', '5'); 

      if ($exported) {
        setcookie('export_ns', MD5('export_ns'), time()+60*$export_time);
        $msg = JText::_( 'NS File Exported' ) . '. <a href="components/com_nspro/uploads/getns.php" target="_blank">'.JText::_('Click to download').'.</a>';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
      }
      else {
        $msg = JText::_( 'Error Exporting NS File' );
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

    }

    function exportxml() {
      $file = 'components/com_nspro/uploads/export_list.xml';

      $exported = $this->doexport($file, 'writexml');
      
      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      if ($this->j15 == true) {
        $component = JComponentHelper::getComponent( 'com_nspro' );
        $params = new JParameter( $component->params );
      }

      $export_time  = $params->get('export_time', '5'); 

      if ($exported) {
        setcookie('export_xml', MD5('export_xml'), time()+60*$export_time);
        $msg = JText::_( 'XML File Exported' ) . '. <a href="components/com_nspro/uploads/getxml.php" target="_blank">'.JText::_('Click to download').'.</a>';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
      }
      else {
        $msg = JText::_( 'Error Exporting XML File' );
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

    }

    function importFromJoomla() {

      $model = $this->getModel('subscribers');
      $imported = $model->importFromJoomlaUsers();

      if (is_numeric($imported)) {
        $msg = JText::_( 'Data Imported From Joomla Users' ) . ': ' . $imported . ' ' . JText::_('subscribers added');
      }
      else {
        $msg = JText::_( 'Error Importing From Joomla Users' ).': '.$imported;
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

      $link = 'index.php?option=com_nspro&view=subscribers';
      $this->setRedirect($link, $msg);
    }

    function importtxt() {

      $target_dir = "components/com_nspro/uploads/";

      $target_path = basename( $_FILES['uploadedfile']['name']);

      $target_path = str_replace('/', '', $target_path);

      $allowedTypes = array('txt', 'csv');

      if (!in_array(end(explode(".", strtolower($target_path))), $allowedTypes)) {
        $msg = JText::_( 'Allowed FileTypes: CSV, TXT. Uploaded Filetype not allowed:' ) . ' ' . end(explode(".", strtolower($realname)));
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
        return;
      }

      $uploaded = false;
      if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_dir.$target_path)) {
        $uploaded = true;
      }

      if (!$uploaded) {
        $msg = JText::_( 'Error Uploading File' );
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

      $model = $this->getModel('subscribers');

      $imported = 'Unknown Error';

      if ($_POST["inputtype"] == '1') {
        $imported = $model->importFromTextFile($target_dir.$target_path);
      }
      else if ($_POST["inputtype"] == '2') {
        $imported = $model->importFromExcelFile($target_dir.$target_path);
      }
      else {
        $imported = $model->importFromNSFile($target_dir.$target_path);
      }

      if (is_numeric($imported)) {
        $msg = JText::_( 'Data Imported From Text/Excel File' ) . ': ' . $imported . ' ' . JText::_('subscribers added').'.';
      }
      else {
        $msg = JText::_( 'Error Importing From Text File' ).': '.$imported;
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

      $link = 'index.php?option=com_nspro&view=subscribers';
      $this->setRedirect($link, $msg);
    }

    // MAILING LIST FUNCTIONS

    function ledit()
    {
        JRequest::setVar( 'view', 'listedit' );
        JRequest::setVar( 'layout', 'form'  );
        JRequest::setVar('hidemainmenu', 1);

        parent::display();
    }

    function lsave()
    {
        $model = $this->getModel('lists');

        $link = 'index.php?option=com_nspro';
        if ($model->store()) {
            $msg = JText::_( 'List Saved!' );
            $this->setRedirect($link, $msg);
        } else {
            $msg = JText::_( 'Error Saving List' );
            $this->setRedirect($link, $msg, 'error');
        }
    }

    function lremove()
    {
        $model = $this->getModel('lists');
        if(!$model->delete()) {
            $msg = JText::_( 'Error: One or More Lists Could not be Deleted' );
            $this->setRedirect( 'index.php?option=com_nspro', $msg, 'error');
        } else {
            $msg = JText::_( 'List(s) Deleted' );
            $this->setRedirect( 'index.php?option=com_nspro', $msg );
        }
    }

    function lcancel()
    {
        $msg = JText::_( 'Operation Cancelled' );
        $this->setRedirect( 'index.php?option=com_nspro', $msg );
    }


    function publish()
    {
        $model = $this->getModel('default');

        if ($model->publish(( $this->getTask() == 'publish' ? 1 : 0 ))) {
            $msg = JText::_( 'List(s) Published!' );
            $this->setRedirect( 'index.php?option=com_nspro', $msg );
        } else {
            $msg = JText::_( 'Error Publishing List(s)' );
            $this->setRedirect( 'index.php?option=com_nspro', $msg, 'error');
        }
    }

    function unpublish()
    {
        $model = $this->getModel('default');

        if ($model->publish(( $this->getTask() == 'publish' ? 1 : 0 ))) {
            $msg = JText::_( 'List(s) Unpublished!' );
            $this->setRedirect( 'index.php?option=com_nspro', $msg );
        } else {
            $msg = JText::_( 'Error Unpublishing List(s)' );
            $this->setRedirect( 'index.php?option=com_nspro', $msg, 'error');
        }
    }

    // NEWSLETTER FUNCTIONS

    function nedit()
    {
        JRequest::setVar( 'view', 'newsletteredit' );
        JRequest::setVar( 'layout', 'form'  );
        JRequest::setVar('hidemainmenu', 1);

        parent::display();
    }

    function nsave()
    {
        $model = $this->getModel('newsletters');

        $link = 'index.php?option=com_nspro&view=newsletters';
        if ($model->store()) {
            $msg = JText::_( 'Newsletter Saved!' );
            $this->setRedirect($link, $msg);
        } else {
            $msg = JText::_( 'Error Saving Newsletter' );
            $this->setRedirect($link, $msg, 'error');
        }
    }

    function nremove()
    {
        $model = $this->getModel('newsletters');
        if(!$model->delete()) {
            $msg = JText::_( 'Error: One or More Newsletters Could not be Deleted' );
            $this->setRedirect( 'index.php?option=com_nspro&view=newsletters', $msg, 'error');
        } else {
            $msg = JText::_( 'Newsletter(s) Deleted' );
            $this->setRedirect( 'index.php?option=com_nspro&view=newsletters', $msg );
        }
    }

    function ncancel()
    {
        $msg = JText::_( 'Operation Cancelled' );
        $this->setRedirect( 'index.php?option=com_nspro&view=newsletters', $msg );
    }

    function nsend() {
      $model = $this->getModel('newsletters');

      $nresult = $model->send($_POST);

      $link = 'index.php?option=com_nspro&view=newsletters';
      if ($nresult === true) {
          $msg = JText::_( 'Message(s) sent!' );
          $this->setRedirect($link, $msg);
      } else {
          $msg = JText::_( 'Error Sending Messages' ) . ': ' . $nresult . '.' . JText::_( 'Please check the' ) . ' <a href="components/com_nspro/error_report.txt" target="_blank">' . JText::_( 'error report file' ) . '</a>.';
          $this->setRedirect($link, $msg, 'error');
      }
    }

    function nclearsending() {
      $model = $this->getModel('newsletters');

      $link = 'index.php?option=com_nspro&view=newsletters';
      if(!$model->clearsending()) {
        $msg = JText::_( 'Error: One or More Newsletters Could not have their Sending Status Cleared' );
        $this->setRedirect($link, $msg, 'error');
      } else {
        $msg = JText::_( 'Sending Status of Newsletter(s) Cleared' );
         $this->setRedirect($link, $msg);
      }
    }

    function nduplicate() {
      $model = $this->getModel('newsletters');

      $link = 'index.php?option=com_nspro&view=newsletters';
      if(!$model->createduplicate()) {
        $msg = JText::_( 'Error: One or More Newsletters Could not be Duplicated' );
        $this->setRedirect($link, $msg, 'error');
      } else {
        $msg = JText::_( 'Newsletter(s) Duplicated' );
        $this->setRedirect($link, $msg);
      }
    }

    function attachfile() {

      $db =& JFactory::getDBO();

      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      
      if ($this->j15 == true) {
        $component = JComponentHelper::getComponent( 'com_nspro' );
        $params = new JParameter( $component->params );
      }

      $target_dir = JPATH_ADMINISTRATOR.DS."components/com_nspro/uploads/";

      $msg = JText::_( 'Attachment(s) uploaded successfully' );

      $mfiletypes = $params->get('upfiletypes', 'jpg;jpeg;png;bmp;pdf;gif;txt;csv;zip;doc;rar;7z;wmv;wma;mp3;xls;xml;htm;html;psd;');

      $attachment_security_on = true;

      if ($attachment_security_on) {
        $mfiletypes = JString::str_ireplace(array(';php', 'php;', 'html;', ';html', 'asp;', ';asp', ';aspx', 'aspx;', 'js;', ';js', ';jsp', 'jsp;', 'shtml;', ';shtml', 'xhtml;', ';xhtml', ';java', 'java;', ';swf', 'swf;', ';pl', 'pl;', 'htm;', ';htm', 'cgi;', ';cgi', 'class;', ';class', 'cfm;', ';cfml', 'shtm;', ';shtm', 'php3;', ';php3'), '', $mfiletypes);
      }

      $allowedTypes = explode(';', strtolower($mfiletypes));

      for ($i = 0; $i < 5; $i ++) {
        $uploaded = false;
        if ($_FILES['file_' . $i]) {
          $realname = basename( $_FILES['file_' . $i]['name']);

          if (!in_array(end(explode(".", strtolower($realname))), $allowedTypes)) {
            $msg = JText::_( 'Attachment Filetype not allowed:' ) . ' ' . end(explode(".", strtolower($realname)));
            $link = 'index.php?option=com_nspro&view=newsletters&task=nedit&cid[]=' . $_POST['newsletter_id'];
            $this->setRedirect($link, $msg);
            return;
          }

          $target_path = $realname;
          $target_path = str_replace('/', '', $target_path);
          if(move_uploaded_file($_FILES['file_' . $i]['tmp_name'], $target_dir.$target_path)) {
            $uploaded = true;
          }

          if (!$uploaded) {
            //$msg = JText::_( 'Error Uploading Attachments' );
            // seems that I come here even if the file is uploaded.
            // so im just going to leave it like that for the moment.
            break;
          }

          if ($uploaded) {
            $query = 'INSERT INTO `#__nspro_newsletter_attachments` (`newsletter_id`, `filename`) ' .
                     'VALUES ("'. mysql_escape_string($_POST['newsletter_id']) .'", "'.mysql_escape_string($realname).'")';
            $db->setQuery($query);
            $db->Query();
          }
        }
      }

      $link = 'index.php?option=com_nspro&view=newsletters&task=nedit&cid[]=' . $_POST['newsletter_id'];
      $this->setRedirect($link, $msg);
    }

    function deleteattachments() {

      $db =& JFactory::getDBO();

      $target_dir = JPATH_ADMINISTRATOR.DS."components/com_nspro/uploads/";

      $msg = JText::_( 'Attachment(s) Deleted Successfully' );

      $link = 'index.php?option=com_nspro&view=newsletters&task=nedit&cid[]=' . $_POST['newsletter_id'];
      $attachment_ids = $_POST['attachment'];
      foreach($attachment_ids as $aid) {

        $query = 'SELECT * FROM `#__nspro_newsletter_attachments` WHERE `id` = ' . mysql_escape_string($aid);
        $db->setQuery($query);
        $mat = $db->loadObject();
        unlink($target_dir.$mat->filename);

        $query = 'DELETE FROM `#__nspro_newsletter_attachments` WHERE `id` = ' . mysql_escape_string($aid);
        $db->setQuery($query);
        if (!$db->Query()) {
          $msg = JText::_( 'Error Deleting Attachment(s)' );
          $this->setRedirect($link, $msg, 'error');
        }
      }
      $this->setRedirect($link, $msg);
    }

    // TEMPLATE FUNCTIONS

    function tedit()
    {
        JRequest::setVar( 'view', 'templateedit' );
        JRequest::setVar( 'layout', 'form'  );
        JRequest::setVar('hidemainmenu', 1);

        parent::display();
    }

    function tsave()
    {
        $model = $this->getModel('templates');

        $link = 'index.php?option=com_nspro&view=templates';
        if ($model->store()) {
            $msg = JText::_( 'Template Saved!' );
            $this->setRedirect($link, $msg);
        } else {
            $msg = JText::_( 'Error Saving Template' );
            $this->setRedirect($link, $msg, 'error');
        }
    }

    function tremove()
    {
        $model = $this->getModel('templates');
        $link = 'index.php?option=com_nspro&view=templates';
        if(!$model->delete()) {
            $msg = JText::_( 'Error: One or More Templates Could not be Deleted' );
            $this->setRedirect($link, $msg, 'error');
        } else {
            $msg = JText::_( 'Template(s) Deleted' );
            $this->setRedirect($link, $msg );
        }
    }

    function tcancel()
    {
        $msg = JText::_( 'Operation Cancelled' );
        $this->setRedirect( 'index.php?option=com_nspro&view=templates', $msg );
    }

    // FIELD FUNCTIONS

    function fedit()
    {
        JRequest::setVar( 'view', 'fieldedit' );
        JRequest::setVar( 'layout', 'form'  );
        JRequest::setVar('hidemainmenu', 1);

        parent::display();
    }

    function fsave()
    {
        $model = $this->getModel('fields');

        $link = 'index.php?option=com_nspro&view=fields';
        if ($model->store()) {
            $msg = JText::_( 'Field Saved!' );
            $this->setRedirect($link, $msg);
        } else {
            $msg = JText::_( 'Error Saving Field' );
            $this->setRedirect($link, $msg, 'error');
        }
    }

    function fremove()
    {
        $model = $this->getModel('fields');
        if(!$model->delete()) {
            $msg = JText::_( 'Error: One or More Fields Could not be Deleted' );
            $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg, 'error');
        } else {
            $msg = JText::_( 'Field(s) Deleted' );
            $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg );
        }
    }

    function fcancel()
    {
        $msg = JText::_( 'Operation Cancelled' );
        $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg );
    }

    function fpublish()
    {
        $model = $this->getModel('fields');

        if ($model->publish(( $this->getTask() == 'fpublish' ? 1 : 0 ))) {
            $msg = JText::_( 'Field(s) Published!' );
            $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg );
        } else {
            $msg = JText::_( 'Error Publishing Field(s)' );
            $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg, 'error');
        }
    }

    function funpublish()
    {
        $model = $this->getModel('fields');

        if ($model->publish(( $this->getTask() == 'fpublish' ? 1 : 0 ))) {
            $msg = JText::_( 'Field(s) Unpublished!' );
            $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg );
        } else {
            $msg = JText::_( 'Error Unpublishing Field(s)' );
            $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg, 'error');
        }
    }

    function orderup() {

      $model = $this->getModel('fields');

      if ($model->orderup()) {
        $msg = JText::_('Fields Re-Ordered');
        $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg );
      }
      else {
        $msg = JText::_( 'Error Re-Ordering Fields' );
        $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg, 'error');
      }
    }

    function orderdown() {

      $model = $this->getModel('fields');

      if ($model->orderdown()) {
        $msg = JText::_('Fields Re-Ordered');
        $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg );
      }
      else {
        $msg = JText::_( 'Error Re-Ordering Fields' );
        $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg, 'error');
      }
    }

    function saveorder() {
      $model = $this->getModel('fields');

      if ($model->saveorder()) {
        $msg = JText::_('New Ordering Saved');
        $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg );
      }
      else {
        $msg = JText::_( 'Error Saving New Ordering' );
        $this->setRedirect( 'index.php?option=com_nspro&view=fields', $msg, 'error');
      }
    }
    
    // MIGRATION FUNCTIONS
    
    function export_migration() {
    
      $db =& JFactory::getDBO();
      
      $db->setQuery('SELECT * FROM `#__nspro_subs` ORDER BY `id`');      
      $subs = $db->loadObjectList();
      
      $db->setQuery('SELECT * FROM `#__nspro_newsletters` ORDER BY `id`');      
      $newsletters = $db->loadObjectList();
      
      $db->setQuery('SELECT * FROM `#__nspro_lists` ORDER BY `id`');      
      $lists = $db->loadObjectList();
      
      $db->setQuery('SELECT * FROM `#__nspro_newsletter_attachments` ORDER BY `id`');      
      $newsletter_attachments = $db->loadObjectList();
      
      $db->setQuery('SELECT * FROM `#__nspro_newsletter_openings` ORDER BY `id`');      
      $newsletter_openings = $db->loadObjectList();
      
      $db->setQuery('SELECT * FROM `#__nspro_html_templates` ORDER BY `id`');      
      $html_templates = $db->loadObjectList();
      
      $db->setQuery('SELECT * FROM `#__nspro_fields` ORDER BY `id`');      
      $fields = $db->loadObjectList();
      
      $db->setQuery('SELECT * FROM `#__nspro_field_values` ORDER BY `id`');      
      $field_values = $db->loadObjectList();
      
      
      header('Content-Description: File Transfer');
      header("Content-Type: text/xml");
      header('Expires: 0');
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      header("Content-Disposition: attachment; filename=nspro_migration.xml");
      //header("Content-Length: " .filesize($file));
      header('Pragma: public');
  
      print '<root>'."\n".'<nspro_xml>'."\n";

      print '<subscribers>'."\n";
      print $this->ObjectListToXML($subs);
      print '</subscribers>'."\n".'<newsletters>'."\n";
      print $this->ObjectListToXML($newsletters);
      print '</newsletters>'."\n".'<lists>'."\n";
      print $this->ObjectListToXML($lists);
      print '</lists>'."\n".'<attachments>'."\n";
      print $this->ObjectListToXML($newsletter_attachments);
      print '</attachments>'."\n".'<openings>'."\n";
      print $this->ObjectListToXML($newsletter_openings);
      print '</openings>'."\n".'<templates>'."\n";
      print $this->ObjectListToXML($html_templates);
      print '</templates>'."\n".'<fields>'."\n";
      print $this->ObjectListToXML($fields);
      print '</fields>'."\n".'<values>'."\n";
      print $this->ObjectListToXML($field_values);
      print '</values>'."\n";

      print '</nspro_xml>'."\n".'</root>';
    
      exit(0);
      //$msg = JText::_('Migration File Exported');
      //$this->setRedirect( 'index.php?option=com_nspro&view=toolkit', $msg );
    }
    
    function ObjectListToXML($list) {
      $result = '';
      // list to xml
      if (count($list) > 0) {
        foreach($list as $item) {
          $mvars = get_object_vars($item);
          $result .= '  <object id="'.$item->id.'">'."\n";
          foreach($mvars as $key => $value) {
            $result .= '    <'.$key.'>';
            $useCData = ((strpos($value, '<') !== false) || (strpos($value, '>') !== false) || (strpos($value, '&') !== false));
            if ($useCData == true) {
              $result .= '<![CDATA[';
            }
            $result .= $value;
            if ($useCData == true) {
              $result .= ']]>';
            }
            $result .= '</'.$key.'>'."\n";
          }
          $result .= '  </object>'."\n";
        }
      }
      return $result;
    }
    
    function import_migration() {
      $db =& JFactory::getDBO();

      // upload the file
      $target_dir = JPATH_ADMINISTRATOR.DS."components/com_nspro/uploads/";
      
      if (isset($_FILES['nspro_migration'])) {
        $realname = basename( $_FILES['nspro_migration']['name']);
        
        $extension = end(explode(".", strtolower($realname)));
        
        if ($extension != 'xml') {
          $msg = JText::_( 'Migration File is XML format only.' );
          $link = 'index.php?option=com_nspro&view=toolkit';
          $this->setRedirect($link, $msg, 'error');
          return;
        }

        $target_path = str_replace('/', '', $realname);
        if(move_uploaded_file($_FILES['nspro_migration']['tmp_name'], $target_dir.$target_path)) {
          $uploaded = true;
        }

        if ($uploaded) {      
					// load the file
					$xml = simplexml_load_file($target_dir.$target_path);    
					$subscribers = $xml->nspro_xml->subscribers;
					$newsletters = $xml->nspro_xml->newsletters;
					$lists       = $xml->nspro_xml->lists;
					$attachments = $xml->nspro_xml->attachments;
					$openings    = $xml->nspro_xml->openings;
					$templates   = $xml->nspro_xml->templates;
					$fields      = $xml->nspro_xml->fields;
					$values      = $xml->nspro_xml->values;

					if (count($subscribers) > 0) {
						foreach($subscribers->children() as $object) {
							$this->ObjectToDB($db, '#__nspro_subs', $object);
						}
					}

					if (count($newsletters) > 0) {
						foreach($newsletters->children() as $object) {
							$this->ObjectToDB($db, '#__nspro_newsletters', $object);
						}
					}

					if (count($lists) > 0) {
						foreach($lists->children() as $object) {
							$this->ObjectToDB($db, '#__nspro_lists', $object);
						}
					}      

					if (count($attachments) > 0) {
						foreach($attachments->children() as $object) {
							$this->ObjectToDB($db, '#__nspro_newsletter_attachments', $object);
						}
					}      

					if (count($openings) > 0) {
						foreach($openings->children() as $object) {
							$this->ObjectToDB($db, '#__nspro_newsletter_openings', $object);
						}
					}      
					
					if (count($templates) > 0) {
						foreach($templates->children() as $object) {
							$this->ObjectToDB($db, '#__nspro_html_templates', $object);
						}
					}     					

					if (count($fields) > 0) {
						foreach($fields->children() as $object) {
							$this->ObjectToDB($db, '#__nspro_fields', $object);
						}
					}     

					if (count($values) > 0) {
						foreach($values->children() as $object) {
							$this->ObjectToDB($db, '#__nspro_field_values', $object);
						}
					}  
					
          $msg = JText::_('Migration File Imported');
          $this->setRedirect( 'index.php?option=com_nspro&view=toolkit', $msg );					
			  } // end if uploaded
			} // end if isset FILES
			else {
        $msg = JText::_( 'No file found.' );
        $link = 'index.php?option=com_nspro&view=toolkit';
        $this->setRedirect($link, $msg);
        return;
			}
    }    
    
    function ObjectToDB($db, $table, $object) {
      $query = 'INSERT INTO `'.$table.'` ';
      $mvars = get_object_vars($object);
      $query .= '(';
      foreach($mvars as $key => $value) {
        if ($key != '@attributes') {
          $query .= '`'.$key.'`, ';
        }
      }
      $query = rtrim($query, ' ,');
      $query .= ') VALUES (';
      foreach($mvars as $key => $value) {
        if ($key != '@attributes') {
          $query .= '"'.mysql_escape_string($value).'", ';
        }
      }      
      $query = rtrim($query, ' ,');
      $query .= ')';
      $db->setQuery($query);
      $db->query();
    }
    
    function sub_stats() {
      $db =& JFactory::getDBO();
      
      $db->setQuery('SELECT DATE_FORMAT(`datetime`, "%Y-%m-%d") as `datetime` from `#__nspro_subs` WHERE `confirmed` = true ORDER BY `datetime` ASC LIMIT 1');      
      $first_date = $db->loadResult();

      $db->setQuery('SELECT DATE_FORMAT(`datetime`, "%Y-%m-%d") as `datetime` from `#__nspro_subs` WHERE `confirmed` = true ORDER BY `datetime` DESC LIMIT 1');      
      $last_date = $db->loadResult();
      
      $db->setQuery('SELECT * FROM `#__nspro_lists`');
      $lists = $db->loadObjectList();

      ?>
      <script type="text/javascript"><!--
      
      function changeStats() {
        var newsrc = 'index.php?option=com_nspro&task=print_sub_statistics';
        newsrc = newsrc + '&width=780&height=350&wrv=true';
        
        var mlist_ids = document.getElementById('list_ids');
        var mstring = '';
        var j = 0;
        for (var i=0; i < mlist_ids.options.length;i++) {
          if (mlist_ids.options[i].selected) {
              mstring = mstring + '&list_ids['+j+']='+mlist_ids.options[i].value;
              j++;
          }
        }
        
        if (mstring != '') {
          newsrc = newsrc + mstring;
        }
        
        var smg = document.getElementById('show_main_graph').checked;
        if (smg != true) { // this is correct, because we pass the hide instead of the show
          newsrc = newsrc+'&hmg=true';
        }

        var from_date = document.getElementById('from_date').value;
        newsrc = newsrc + '&from_date='+from_date;
        
        var to_date = document.getElementById('to_date').value;
        newsrc = newsrc + '&to_date='+to_date;
        
        var img = document.getElementById('img_SubChart2');
        img.setAttribute('src', newsrc);
        
        return false;
      }
      
      --></script>
      <div id="nspro_sub_stats_container">
      <fieldset class="nspro stats" style="width: 780px;">
      <legend><?php print JText::_('Analytic Subscriber Statistics'); ?></legend>
      <form action="index.php" name="subStatsForm">
        <table border="0" style="border-collapse: separate; border-spacing: 5px;">
          <tr><td class="key"><?php print JText::_('From Date'); ?>: </td><td>
          <?php
            print JHTML::_('calendar', $first_date, 'from_date', 'from_date', '%Y-%m-%d', 'class="inputbox calendar"');
          ?></td>
          <td class="key" rowspan="2" valign="top"><?php print JText::_('Mailing Lists'); ?></td>
          <td rowspan="2"><select multiple="multiple" rows="4" name="list_ids" id="list_ids" style="width: 300px;">
          <?php
            if (count($lists) > 0) {
              foreach($lists as $list) {
                print '<option value="'.$list->id.'">'.$list->lname.'</option>';
              }
            }
          ?>
          </select></td>
          <td class="key"><?php print JText::_('Show Total Subscription Graph'); ?></td>
          <td><input type="checkbox" id="show_main_graph" name="show_main_graph" checked="checked"/></td>
          </tr>
          <tr><td class="key"><?php print JText::_('To Date'); ?>: </td><td>
          <?php
            print JHTML::_('calendar', $last_date, 'to_date', 'to_date', '%Y-%m-%d', 'class="inputbox calendar"');
          ?></td>
          <td colspan="2" align="right"><input type="button" onClick="javascript:changeStats();" value="<?php print JText::_('Filter Statistics'); ?>" class="button"/></td>
          </tr>
          </table>
      </form>
      </fieldset>
      <br/>
      <?php
        $src = 'index.php?option=com_nspro&task=print_sub_statistics'.
               '&amp;width=780&amp;height=350&wrv=true';
      ?>
      <img id="img_SubChart2" src='<?php print $src; ?>'/>
      </div>
    <?php
    }
    
    function print_sub_conf_pie() {
      // Include pChart      
      include("components/com_nspro/pChart/pData.class");
      include("components/com_nspro/pChart/pChart.class");
      include("components/com_nspro/pChart/pCache.class");
      
      $confarray = array('Confirmed', 'Not Confirmed');
      $db =& JFactory::getDBO();
      
      $db->setQuery('SELECT COUNT(*) FROM `#__nspro_subs` WHERE `confirmed` = true');
      $conf = $db->loadResult();
      
      $db->setQuery('SELECT COUNT(*) FROM `#__nspro_subs` WHERE `confirmed` = false');
      $noconf = $db->loadResult();
      
      $confvalues = array($conf, $noconf);
      
			$DataSet = new pData;
			$DataSet->AddPoint($confvalues,"Serie1");
			$DataSet->AddPoint($confarray,"Serie2");
			$DataSet->AddAllSeries();
		  $DataSet->SetAbsciseLabelSerie("Serie2");

      $Cache = new pCache("components/com_nspro/pChart/data");  
      $Cache->GetFromCache('SubPie',$DataSet->GetData()); 

			$Test = new pChart(380,283);
			$Test->loadColorPalette("components/com_nspro/pChart/Sample/softtones.txt");
			$Test->drawFilledRoundedRectangle(7,7,373,278,5,240,240,240);
			$Test->drawRoundedRectangle(5,5,375,280,5,230,230,230);

			$Test->drawFilledCircle(152,160,100,200,200,200);

			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",8);
			$Test->AntialiasQuality = 0;
			$Test->drawBasicPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),150,158,100,PIE_PERCENTAGE,255,255,218);
			$Test->drawPieLegend(265,45,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250);

			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",10);
			$Test->drawTitle(0,20,"NS Pro Confirmed Subscriptions",50,50,50,380);
      $Cache->WriteToCache('SubPie',$DataSet->GetData(),$Test);  
			$Test->Stroke();

			exit(0);
    }
    
    function print_sub_statistics() {
      // Include pChart      
      include("components/com_nspro/pChart/pData.class");
      include("components/com_nspro/pChart/pChart.class");
      include("components/com_nspro/pChart/pCache.class");
      
      $db =& JFactory::getDBO();

      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      
      if ($this->j15 == true) {
        $component = JComponentHelper::getComponent( 'com_nspro' );
        $params = new JParameter( $component->params );
      }
      
      $stats_months = $params->get('stats_months', 18);
      
      $db->setQuery('SELECT DATE_FORMAT(`datetime`, "%Y-%m-%d") as `datetime` from `#__nspro_subs` WHERE `confirmed` = true ORDER BY `datetime` ASC LIMIT 1');      
      $first_date = $db->loadResult();

      $db->setQuery('SELECT DATE_FORMAT(`datetime`, "%Y-%m-%d") as `datetime` from `#__nspro_subs` WHERE `confirmed` = true ORDER BY `datetime` DESC LIMIT 1');      
      $last_date = $db->loadResult();
      
      // Filters
      $list_ids = JRequest::getVar( 'list_ids', array(), 'get', 'array' );      
      $from_date = JRequest::getVar( 'from_date', $first_date, 'get', 'string' );
      $to_date = JRequest::getVar( 'to_date', $last_date, 'get', 'string' );
      $hide_main_graph = JRequest::getVar( 'hmg', false, 'get', 'boolean' ); 
      
      // pCache Chart Name
      $cname = JRequest::getVar( 'cname', 'SubChart2', 'get', 'string' );
      
      $wrv = JRequest::getVar( 'wrv', false, 'get', 'boolean' ); 
      
      // Sizes
      $width = JRequest::getInt('width', '800');
      $height = JRequest::getInt('height', '300');

      $where = ' WHERE `confirmed` = true';
      if ($from_date != $first_date) {
        $where .= ' AND `datetime` >= "'.mysql_escape_string($from_date).'"';
      }
      if ($to_date != $last_date) {
        $where .= ' AND `datetime` <= "'.mysql_escape_string($to_date).'"';
      }
      
      $filter_lists = (count($list_ids) > 0);
      
      // if we bring only the lists, it will not bring all subscribers for the main graph.
      //if ($filter_lists == true) {
      //  $where .= ' AND (';
      //  foreach($list_ids as $lid) {
      //    $where .= '(FIND_IN_SET("'.mysql_escape_string($lid).'", `mailing_lists`) > 0) OR ';
      //  }
      //  $where = rtrim($where, 'RO ');
      //  $where .= ')';
      //}
      
      $order_by = 'ORDER BY `datetime` ASC';
      
      $db->setQuery('SELECT DATEDIFF("'.$from_date.'", "'.$to_date.'") AS DATEDIFFERENCE');
      $date_diff = $db->loadResult();
      
      $date_format = '%b %Y';
      $mymaxmonths = $stats_months*30;
      if (abs($date_diff) > $mymaxmonths) { 
        // more than 18 months
        $date_format = '%Y';
      }
      else if (abs($date_diff) > 30) {
        // more than a month
        $date_format = '%b %Y';
      }
      else if (abs($date_diff) > 1) {
        // less than a month
        $date_format = '%a, %e %b';
      }
      else {
        // less than a day
        $date_format = '%H:%i, %e %b';
      }
			$db->setQuery('SELECT DISTINCT DATE_FORMAT(`datetime`, "'.$date_format.'") FROM `#__nspro_subs` '.$where.' '.$order_by);
			$mykeys = $db->loadResultArray();

      if ($filter_lists == true) {
        $db->setQuery('SELECT `id`, `lname` FROM `#__nspro_lists` WHERE `id` IN ('.mysql_escape_string(implode(',', $list_ids)).')');
        $mylistnames = $db->loadAssocList('id');
      }

			$db->setQuery('SELECT `datetime`, `mailing_lists`, DATE_FORMAT(`datetime`, "'.$date_format.'") AS dm FROM `#__nspro_subs` '.$where.' '.$order_by);
			$myrows = $db->loadObjectList();
			$myvalues = array();
			if ($filter_lists == true) {
			  $mylistvalues = array();
			  foreach($mylistnames as $mlist) {
			    $mylistvalues[$mlist[id]] = array();
			  }
			}
			foreach($myrows as $myrow) {
				if (isset($myvalues[$myrow->dm])) {
					$myvalues[$myrow->dm] = $myvalues[$myrow->dm] + 1;
				}
				else {
					$myvalues[$myrow->dm] = 1;
				}
				if ($filter_lists == true) {
					foreach($mylistnames as $mlist) {
						if (!isset($mylistvalues[$mlist[id]][$myrow->dm])) {
						  $mylistvalues[$mlist[id]][$myrow->dm] = 0;
						}
					}
				  $mylists = explode(',', $myrow->mailing_lists);
				  foreach($mylists as $mylist) {
				    if (!in_array($mylist, $list_ids)) {
				      continue;
				    }
				    if (isset($mylistvalues[$mylist])) {
				      if (isset($mylistvalues[$mylist][$myrow->dm])) {
					      $mylistvalues[$mylist][$myrow->dm] = $mylistvalues[$mylist][$myrow->dm] + 1; 
					    }
					    else {
					      $mylistvalues[$mylist][$myrow->dm] = 1;
					    }
					  }
					  else {
					  	$mylistvalues[$mylist] = array();
					  	$mylistvalues[$mylist][$myrow->dm] = 1;
					  }		
				  }	  
				}
			}
			
			if ((count($myrows) == 0) || (($hide_main_graph == true) && (count($mylistvalues) == 0))) {
			  header("Content-Type: image/png");
        $im = @imagecreate($width, $height) or die("Cannot Initialize new GD image stream");
        $background_color = imagecolorallocate($im, 255, 255, 255);
        $text_color = imagecolorallocate($im, 0, 0, 0);
        imagestring($im, 5, 5, 5,  JText::_("No subscribers found"), $text_color);
        imagepng($im);
        imagedestroy($im);
			  exit(0);
			}
      
			$DataSet = new pData;
			if ($hide_main_graph != true) {
			  $DataSet->AddPoint($myvalues,"Serie1");
			}
			if ($filter_lists == true) {
				foreach($mylistvalues as $key => $value) {
			//		$DataSet->AddPoint($mylistvalues[$mlist->id],$mlist->lname);
			    foreach($value as $point) {
			      $DataSet->AddPoint($point, $mylistnames[$key][lname]);
			    }
				}
			}
			$DataSet->AddPoint($mykeys,"Serie3");
			if ($hide_main_graph != true) {
			  $DataSet->AddSerie("Serie1");
			}
			if ($filter_lists == true) {
				$added = array();
				foreach($mylistvalues as $key => $value) {
			//		$DataSet->AddSerie($mlist->lname);
			    if (!in_array($key, $added)) {
			      $DataSet->AddSerie($mylistnames[$key][lname]);
			      $added[] = $key;
			    }
				}
			}
			$DataSet->SetAbsciseLabelSerie("Serie3");
			if ($hide_main_graph != true) {
			  $DataSet->SetSerieName("Subscriptions","Serie1");
			}
			$DataSet->SetYAxisName("Subscriptions");

      $Cache = new pCache("components/com_nspro/pChart/data");  
      $Cache->GetFromCache($cname,$DataSet->GetData()); 

			// Initialise the graph
			// original width: 800, original height: 283
			$Test = new pChart($width,$height);
			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",8);
			$Test->setGraphArea(85,30,$width-50,$height-43);
			$Test->drawFilledRoundedRectangle(7,7,$width-7,$height-5,5,240,240,240);
			$Test->drawRoundedRectangle(5,5,$width-5,$height-3,5,230,230,230);
			$Test->drawGraphArea(255,255,255,TRUE);
			$Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,130,130,130,TRUE,0,2);
			$Test->drawGrid(4,TRUE,230,230,230,50);

			// Draw the 0 line
			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",6);
			$Test->drawTreshold(0,143,55,72,TRUE,TRUE);

			// Draw the line graph
			$Test->drawLineGraph($DataSet->GetData(),$DataSet->GetDataDescription());
			$Test->drawPlotGraph($DataSet->GetData(),$DataSet->GetDataDescription(),3,2,255,255,255);

      if ($wrv == true) {
        $Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",8);     
        $Test->writeValues($DataSet->GetData(),$DataSet->GetDataDescription(),"Serie1");
				$added = array();
				foreach($mylistvalues as $key => $value) {
			    if (!in_array($key, $added)) {
			      $Test->writeValues($DataSet->GetData(),$DataSet->GetDataDescription(),$mylistnames[$key][lname]);
			      $added[] = $key;
			    }
				}        
      }
			
			// Finish the graph
			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",8);
			$Test->drawLegend(90,35,$DataSet->GetDataDescription(),255,255,255);
			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",10);
			$Test->drawTitle(60,22,"NS Pro Subscription Graph",50,50,50,775);
			$Cache->WriteToCache($cname,$DataSet->GetData(),$Test);  
      $Test->Stroke();
			
      exit(0);
    }       
    
    function print_email_pie() {
      // Include pChart      
      include("components/com_nspro/pChart/pData.class");
      include("components/com_nspro/pChart/pChart.class");
      include("components/com_nspro/pChart/pCache.class");
    
      $db =& JFactory::getDBO();
      $db->setQuery('SELECT `nid`, SUM(`openings`) as `openings` FROM `#__nspro_newsletter_openings` GROUP BY `nid`');
      $results = $db->loadObjectList();
      
      if (count($results) < 2) {
			  header("Content-Type: image/png");
        $im = @imagecreate(380, 283) or die("Cannot Initialize new GD image stream");
        $background_color = imagecolorallocate($im, 255, 255, 255);
        imagepng($im);
        imagedestroy($im);
			  exit(0);        
      }
      else {
        $email_open_ids = array();
        $email_openings = array();
        foreach($results as $result) {
          $email_open_ids[$result->nid] = JText::_('Email ID').': '.$result->nid; 
          $email_openings[$result->nid] = $result->openings;
        }
      }
      
			$DataSet = new pData;
			$DataSet->AddPoint($email_openings,"Serie1");
			$DataSet->AddPoint($email_open_ids,"Serie2");
			$DataSet->AddAllSeries();
			$DataSet->SetAbsciseLabelSerie("Serie2");

      $Cache = new pCache("components/com_nspro/pChart/data");  
      $Cache->GetFromCache('EmailPie2',$DataSet->GetData()); 
      
			$Test = new pChart(380,283);  
			$Test->loadColorPalette("components/com_nspro/pChart/Sample/softtones.txt");
			$Test->drawFilledRoundedRectangle(7,7,373,276,5,240,240,240);  
			$Test->drawRoundedRectangle(5,5,375,278,5,230,230,230);  
			
			// Draw the pie chart  
			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",8);
			$Test->drawPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),160,140,140,PIE_PERCENTAGE,TRUE,50,20,5);  
			$Test->drawPieLegend(265,25,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250);        
      
			//$Test = new pChart(380,283);
			//$Test->loadColorPalette("components/com_nspro/pChart/Sample/softtones.txt");
			//$Test->drawFilledRoundedRectangle(7,7,373,278,5,240,240,240);
			//$Test->drawRoundedRectangle(5,5,375,280,5,230,230,230);

			//$Test->drawFilledCircle(152,160,100,200,200,200);

			//$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",8);
			//$Test->AntialiasQuality = 0;
			//$Test->drawBasicPieGraph($DataSet->GetData(),$DataSet->GetDataDescription(),150,158,100,PIE_PERCENTAGE,255,255,218);
			//$Test->drawPieLegend(265,45,$DataSet->GetData(),$DataSet->GetDataDescription(),250,250,250);

			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",10);
			$Test->drawTitle(0,20,"NS Pro Email Openings",50,50,50,380);
			$Cache->WriteToCache('EmailPie2',$DataSet->GetData(),$Test);  
      $Test->Stroke();
      
      exit(0);
    }
    
    function print_email_chart() {
      // Include pChart      
      include("components/com_nspro/pChart/pData.class");
      include("components/com_nspro/pChart/pChart.class");
      include("components/com_nspro/pChart/pCache.class");
      
      // Filters
      $email_ids = JRequest::getVar( 'email_ids', array(), 'get', 'array' );   

      // pCache Chart Name
      $cname = JRequest::getVar( 'cname', 'EmailChart2', 'get', 'string' );
      
      // Sizes
      $width = JRequest::getInt('width', '800');
      $height = JRequest::getInt('height', '300');
      
      $filter_ids = (count($email_ids) > 0);
      
      $where = '';
      if ($filter_ids == true) {
        $where = 'WHERE `nid` IN (';
        foreach($email_ids as $nid) {
          $where .= '"'.mysql_escape_string($nid).'", ';
        }
        $where = rtrim($where, ' ,');
        $where .= ')';
      }
      
      $db =& JFactory::getDBO();
      $db->setQuery('SELECT `nid`, SUM(`openings`) as `openings`, COUNT(`email`) as `uniques` FROM `#__nspro_newsletter_openings` '.$where.' GROUP BY `nid`');
      $results = $db->loadObjectList();
      
      if (count($results) == 0) {
			  header("Content-Type: image/png");
        $im = @imagecreate($width, $height) or die("Cannot Initialize new GD image stream");
        $background_color = imagecolorallocate($im, 255, 255, 255);
        $text_color = imagecolorallocate($im, 0, 0, 0);
        imagestring($im, 5, 5, 5,  JText::_("No newsletters found"), $text_color);
        imagepng($im);
        imagedestroy($im);
			  exit(0);       
      }
      else if (count($results) == 1) {
        $email_open_ids = array(0);
        $email_openings = array(0);
        $email_uniques  = array(0);
        foreach($results as $result) {
          $email_open_ids[$result->nid] = JText::_('Email ID').': '.$result->nid; 
          $email_openings[$result->nid] = $result->openings;
          $email_uniques[$result->nid]  = $result->uniques;
        }
      }
      else {
        $email_open_ids = array();
        $email_openings = array();
        $email_uniques  = array();
        foreach($results as $result) {
          $email_open_ids[$result->nid] = JText::_('Email ID').': '.$result->nid; 
          $email_openings[$result->nid] = $result->openings;
          $email_uniques[$result->nid]  = $result->uniques;
        }
      }
    
			// Dataset definition
			$DataSet = new pData;
			$DataSet->AddPoint($email_openings,"Serie1");
			$DataSet->AddPoint($email_open_ids,"Serie2");
			$DataSet->AddPoint($email_uniques,"Serie3");
			$DataSet->SetAbsciseLabelSerie("Serie2");
			$DataSet->AddSerie("Serie1");
			$DataSet->AddSerie("Serie3");
			$DataSet->SetSerieName("Times Viewed","Serie1");
			$DataSet->SetSerieName("Unique Email Addresses","Serie3");
			$DataSet->SetYAxisName("Email Openings");

      $Cache = new pCache("components/com_nspro/pChart/data");  
      $Cache->GetFromCache($cname,$DataSet->GetData()); 
      
			// Initialise the graph
			// Original 700x283
			$Test = new pChart($width,$height);
			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",8);
			$Test->setGraphArea(85,30,$width-50,$height-43);
			$Test->drawFilledRoundedRectangle(7,7,$width-7,$height-5,5,240,240,240);
			$Test->drawRoundedRectangle(5,5,$width-5,$height-3,5,230,230,230);
			$Test->drawGraphArea(255,255,255,TRUE);
			$Test->drawScale($DataSet->GetData(),$DataSet->GetDataDescription(),SCALE_START0,150,150,150,TRUE,0,2,TRUE);
			$Test->drawGrid(4,TRUE,230,230,230,50);

			// Draw the 0 line
			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",6);
			$Test->drawTreshold(0,143,55,72,TRUE,TRUE);

			// Draw the bar graph
			//$Test->drawBarGraph($DataSet->GetData(),$DataSet->GetDataDescription(),TRUE,80);
			$Test->drawOverlayBarGraph($DataSet->GetData(),$DataSet->GetDataDescription());

      $Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",8);     
      $Test->writeValues($DataSet->GetData(),$DataSet->GetDataDescription(),array("Serie1", "Serie3"));
      
			// Finish the graph
			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",8);
			$Test->drawLegend(90,35,$DataSet->GetDataDescription(),255,255,255);
			$Test->setFontProperties("components/com_nspro/pChart/Fonts/tahoma.ttf",10);
			$Test->drawTitle(50,22,"NS Pro Email Opening Bar Graph",50,50,50,675);
			$Cache->WriteToCache($cname,$DataSet->GetData(),$Test);  
      $Test->Stroke();
      
      exit(0);
    }
    
    function newsletter_stats() {
      $db =& JFactory::getDBO();
      
      $db->setQuery('SELECT A.`nid`, B.`id`, B.`subject` FROM `#__nspro_newsletter_openings` A'.
                    ' LEFT JOIN `#__nspro_newsletters` B ON A.`nid` = B.`id` GROUP BY A.`nid`');
      
		  $newsletters_with_openings = $db->loadObjectList();
		  
      ?>
      <script type="text/javascript"><!--
      
      function changeStats() {
        var newsrc = 'index.php?option=com_nspro&task=print_email_chart';
        newsrc = newsrc + '&width=780&height=350&cname=Email_Chart2';
        
        var memail_ids = document.getElementById('email_ids');
        var mstring = '';
        var j = 0;
        for (var i=0; i < memail_ids.options.length;i++) {
          if (memail_ids.options[i].selected) {
              mstring = mstring + '&email_ids['+j+']='+memail_ids.options[i].value;
              j++;
          }
        }
        
        if (mstring != '') {
          newsrc = newsrc + mstring;
        }
                
        var img = document.getElementById('img_EmailChart2');
        img.setAttribute('src', newsrc);
        
        return false;
      }
      
      --></script>
      <div id="nspro_email_stats_container">
      <fieldset class="nspro stats" style="width: 780px;">
      <legend><?php print JText::_('Analytic Email View Statistics'); ?></legend>
      <form action="index.php" name="subStatsForm">
        <table border="0" style="border-collapse: separate; border-spacing: 5px;">
          <tr>
          <td class="key" valign="top"><?php print JText::_('Emails to Show'); ?></td>
          <td><select multiple="multiple" rows="4" name="email_ids" id="email_ids" style="width: 500px;">
          <?php
            if (count($newsletters_with_openings) > 0) {
              foreach($newsletters_with_openings as $nsl) {
                print '<option value="'.$nsl->id.'">'.$nsl->id.': '.$nsl->subject.'</option>';
              }
            }
          ?>
          </select></td>
          <td align="right" valign="bottom"><input type="button" onClick="javascript:changeStats();" value="<?php print JText::_('Filter Statistics'); ?>" class="button"/></td>
          </tr>
          </table>
      </form>
      </fieldset>
      <br/>
      <?php
        $src = 'index.php?option=com_nspro&task=print_email_chart'.
               '&amp;width=780&amp;height=350&cname=Email_Chart2';
      ?>
      <img id="img_EmailChart2" src='<?php print $src; ?>'/>
      </div>
    <?php
    }
    
}
?>